package cn.mineserv.video.videoordersystem.utils;

import org.springframework.util.FileCopyUtils;
import org.springframework.util.MimeType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.Part;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author 爱吃蛋白的丶圆周率
 * @company 圆周率有限公司
 */
public class FileUtil {
    public static final String FILE_PATH = "D:\\ProjectAndResource\\Java\\IDEA\\MangaSystem\\src\\main\\resources\\static\\img\\update\\img\\";
    public static final String SAVE_PATH_SHORT = "/image/update/image/";
    public static final String SAVE_PATH = "D:\\ProjectAndResource\\Java\\IDEA\\MangaSystem\\target\\classes\\static\\img\\update\\img\\";


    public static String uploadFile(MultipartFile multipartFile) {
        String newFileName = "";
        try{
            if(!multipartFile.isEmpty()){
                String contentType = multipartFile.getContentType();
                if(contentType!= null && contentType.contains("image")){
                    // image/png -> .png
                    //文件扩展名
                    MimeType mimeType = MimeType.valueOf(contentType);
                    String extension = mimeType.getSubtype();
                    //构建文件扩展名
                    newFileName = UUID.randomUUID().toString().replace("-", "") + Long.toHexString(System.currentTimeMillis()) + "." +extension;

                    CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
                    byte[] fileBytes = commonsMultipartFile.getBytes();

                    String filepath = FILE_PATH + newFileName;
                    String pathname = SAVE_PATH + newFileName;

                    FileCopyUtils.copy(fileBytes, new File(filepath));
                    FileCopyUtils.copy(fileBytes, new File(pathname));
                }
            }

        } catch (Exception e){
            e.printStackTrace();
        }
        return SAVE_PATH_SHORT+newFileName;
    }

    public static List<String> uploadFiles(Collection<Part> parts) {
        List<String> fileNames = new ArrayList<>();
        try{
            Iterator<Part> iterator = parts.iterator();
            while ((iterator.hasNext())) {
                Part next = iterator.next();
                String contentType = next.getContentType();
                if(contentType!= null && contentType.contains("image")){
                    String fileName = next.getSubmittedFileName();

                    //文件扩展名
                    String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
                    //构建文件扩展名
                    String newFileName = UUID.randomUUID().toString().replace("-", "") + Long.toHexString(System.currentTimeMillis()) + "." +extension;
                    String filepath = FILE_PATH + newFileName;
                    next.write(filepath);
                    fileNames.add(newFileName);
                }

            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return fileNames;
    }

    public static List<String> getAllFileBase64(Collection<Part> parts) {
        List<String> base64List = new ArrayList<>();
        try{
            Iterator<Part> iterator = parts.iterator();
            while ((iterator.hasNext())) {
                Part next = iterator.next();
                String contentType = next.getContentType();
                if(contentType!= null && contentType.contains("image")){
                    InputStream inputStream = next.getInputStream();
                    String base64 = getBase64FromInputStream(inputStream,contentType);
                    base64List.add(base64);
                }

            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return base64List;
    }

    public static String getBase64FromInputStream(InputStream is,String contentType) throws Exception {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;

        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new Exception("输入流关闭异常");
                }
            }
        }

        return "data:"+contentType+";base64,"+Base64.getEncoder().encodeToString(data);
    }

    /**
     * 未完善 输入流转File
     * @param is
     * @param path
     * @param prefix
     * @param suffix
     * @return
     * @throws Exception
     */
    public static File getFileFromInputStream(InputStream is,String path,String prefix,String suffix) throws Exception {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;

        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new Exception("输入流关闭异常");
                }
            }
        }

        File file = new File(path);
        File.createTempFile(prefix,suffix,new File(path));
        file.exists();
        return file;
    }
}
